<template>
  <el-card>
    <template #header>修改密码</template>

    <el-form
      :model="passForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
      size="mini"
    >
      <el-form-item label="原密码" prop="oldPwd">
        <el-input
          type="text"
          v-model="passForm.oldPwd"
          autocomplete="off"
          @blur="checkPass"
        ></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input
          type="text"
          v-model="passForm.password"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirmPwd">
        <el-input
          type="text"
          v-model="passForm.confirmPwd"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >提交</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { checkOldPwd, editPwd } from '@/api/users.js'
import local from '@/utils/local.js'

import {
  validateOldPwd,
  validatePass,
  validatePass2
} from '@/utils/validate.js'

export default {
  data() {
    return {
      // 1.0 数据对象
      passForm: {
        oldPwd: '',
        password: '',
        confirmPwd: ''
      },
      // 2.0 规则对象
      rules: {
        oldPwd: [{ validator: validateOldPwd, trigger: 'blur' }],
        password: [{ validator: validatePass(this), trigger: 'blur' }],
        confirmPwd: [{ validator: validatePass2(this), trigger: 'blur' }]
      },

      // 来记录原密码是否正确的标记
      flag: false
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          // 一个是要满足所有的表单的正则验证
          // 一个是要满足原密码的正确
          if (!this.flag) return ''
          const { code } = await editPwd({
            newPwd: this.passForm.password
          })
          // console.log(data)
          if (code === 0) {
            // 清除本地缓存，然后跳转登录
            local.cls()
            this.$router.push('/')
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    async checkPass() {
      const { code } = await checkOldPwd({
        oldPwd: this.passForm.oldPwd
      })
      // console.log(data)
      if (code === '00') {
        this.flag = true
      } else {
        this.flag = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 300px;

  .el-input {
    width: 178px;
  }
}
</style>
